// utils/router.js
const whiteList = [
  '/pages/login/login', 
  '/pages/register/register'
];

/**
 * 校验登录态
 * @param {string} url — 要跳转的页面路径（不含域名）
 * @returns {boolean} — true: 允许跳转；false: 已自动跳到登录页
 */
function checkAuth(url) {
  const token = wx.getStorageSync('token');
  if (!token && !whiteList.includes(url)) {
    wx.showToast({ title: '请先登录', icon: 'none' });
    wx.navigateTo({ url: '/pages/login/login' });
    return false;
  }
  return true;
}

/**
 * 封装 navigateTo
 */
function navigateTo(options) {
  if (typeof options === 'string') {
    options = { url: options };
  }
  if (checkAuth(options.url)) {
    wx.navigateTo(options);
  }
}

/**
 * 封装 redirectTo
 */
function redirectTo(options) {
  if (typeof options === 'string') {
    options = { url: options };
  }
  if (checkAuth(options.url)) {
    wx.redirectTo(options);
  }
}

/**
 * 其他路由同理：reLaunch、switchTab
 */
function reLaunch(options) {
  if (typeof options === 'string') {
    options = { url: options };
  }
  if (checkAuth(options.url)) {
    wx.reLaunch(options);
  }
}

function switchTab(options) {
  if (typeof options === 'string') {
    options = { url: options };
  }
  // tabBar 页面一般不需要登录态，也可根据业务决定是否校验
  wx.switchTab(options);
}

module.exports = {
  navigateTo,
  redirectTo,
  reLaunch,
  switchTab
};